package com.spzx.order.receiver;


import com.rabbitmq.client.Channel;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.common.rabbit.service.RabbitService;
import com.spzx.order.configure.DelayedMqConfig;
import com.spzx.order.domain.OrderInfo;
import com.spzx.order.service.OrderInfoService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;



@Component
public class OrderInfoReceiver {

    @Autowired
    private OrderInfoService orderInfoService;


    @Autowired
    private RabbitService rabbitService;


    @RabbitListener(queues = DelayedMqConfig.queue_delay_1)
    public void AlertOrderStatus(Channel channel, Object msg, Message message) throws IOException {

        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        byte[] body = message.getBody();
        String orderId = new String(body);
        OrderInfo order = orderInfoService.getOrderInfo(Long.parseLong(orderId));
        Integer orderStatus = order.getOrderStatus();
        try{
            if(orderStatus == 0){//幂等性判断
                OrderInfo orderInfo = new OrderInfo();
                orderInfo.setId(Long.parseLong(orderId));
                orderInfo.setOrderStatus(-1);
                orderInfoService.updateById(orderInfo);
            }
            channel.basicAck(deliveryTag, false);
        }catch (Exception e){
            channel.basicNack(deliveryTag, false, true);
        }finally {
            //订单过期，释放库存
            rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT, MqConst.ROUTING_UNLOCK, order.getOrderNo());
        }
    }
}
